package com.zjuh.goodboy.biz.dataprovider;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.springframework.context.ApplicationContext;

import com.zjuh.goodboy.awires.AppContextAwire;
import com.zjuh.goodboy.context.AppContext;
import com.zjuh.goodboy.index.DataProvider;
import com.zjuh.goodboy.items.Item;
import com.zjuh.goodboy.items.ItemUtil;
import com.zjuh.sweet.sql.util.SqlUtil;

public abstract class AbstractItemDataProvider implements DataProvider, AppContextAwire {

	private AppContext appContext;
	
	private Connection connection;
	
	private PreparedStatement pstmt;
	
	private ResultSet rs;
	
	@Override
	public void destroy() {
		SqlUtil.close(rs);
		SqlUtil.close(pstmt);
		SqlUtil.close(connection);
	}

	@Override
	public boolean hasNext() {
		try {
			return rs.next();
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	public void init() {
		try {
			ApplicationContext springContext = (ApplicationContext)appContext.getObject("springContext");
			DataSource dataSource = (DataSource)springContext.getBean("dataSource");
			connection = dataSource.getConnection();
			pstmt = connection.prepareStatement(getSql());
			rs = pstmt.executeQuery();
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	public Item next() {
		try {
			return ItemUtil.rsToItem(rs);
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	public void setAppContext(AppContext appContext) {
		this.appContext = appContext;
	}

	protected abstract String getSql();
	

}
